package com.legend.utils;

/**
 * Created by ayakatsune on 14-7-12.
 */
//省略包的导入

import com.wh.model.SysUserBase;
import freemarker.cache.FileTemplateLoader;
import freemarker.cache.TemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.apache.log4j.Logger;

import java.io.*;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;


public class FreeMarkerUtils {
    static Logger log = Logger.getRootLogger();


    /**
     * 速度很慢，不建议使用。
     *
     * @param templatePath 模板文件存放路径
     * @param templateName 模板文件名称
     * @param fileName     生成的文件名称
     * @param root
     */
    public static void analysisTemplate1(String templatePath, String templateName, String fileName, Map<?, ?> root) {
        try {
            Configuration config = new Configuration();
            //设置要解析的模板所在的目录，并加载模板文件
            config.setDirectoryForTemplateLoading(new File(templatePath));
            //设置包装器，并将对象包装为数据模型
            config.setObjectWrapper(new DefaultObjectWrapper());

            //获取模板,并设置编码方式，这个编码必须要与页面中的编码格式一致
            //否则会出现乱码
            Template template = config.getTemplate(templateName, "UTF-8");
            //合并数据模型与模板
            FileOutputStream fos = new FileOutputStream(fileName);
            Writer out = new OutputStreamWriter(fos, "UTF-8");
            template.process(root, out);
            out.flush();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TemplateException e) {
            e.printStackTrace();
        }
    }

    /**
     * @param templatePath 模板文件存放路径
     * @param templateName 模板文件名称
     * @param fileName     生成的文件名称
     * @param root
     */
    public static void analysisTemplate(String templatePath, String templateName, String fileName, Map<?, ?> root) {
        try {
            Configuration config = new Configuration();
            //设置要解析的模板所在的目录，并加载模板文件
            config.setDirectoryForTemplateLoading(new File(templatePath));
            //设置包装器，并将对象包装为数据模型
            config.setObjectWrapper(new DefaultObjectWrapper());
            //获取模板,并设置编码方式，这个编码必须要与页面中的编码格式一致
            //否则会出现乱码
            Template template = config.getTemplate(templateName, "UTF-8");
            String tmpDirs = fileName.substring(0, fileName.lastIndexOf("/"));
            File file = new File(tmpDirs);
            if (!file.exists())
                file.mkdirs();
            //合并数据模型与模板
            FileWriter fileWriter = new FileWriter(fileName);
            BufferedWriter writer = new BufferedWriter(fileWriter);
            template.setEncoding("UTF-8");

            template.process(root, writer);
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TemplateException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
//        String template = "oa/web/CodeTmpl/oaTmpl/";
//        MySqlSessionFactory sqlSession = new MySqlSessionFactory();
//        SqlSession session = sqlSession.getSqlSession();
//        String id = "5cf0ef1e-9837-469c-beb6-8af33cfcddc3";
//        ISysTableService service = SysTableService.getInstance();
//        ReturnResult result = service.selectById(id);
//        if (result.getStatus() == Status.SUCCESS) {
//            SysTable table = (SysTable) result.getData();
//            SysTableColumnDao columnDao = session.getMapper(SysTableColumnDao.class);
//            SysTableColumn column = new SysTableColumn();
//            column.setTableName(table.getTableName());
//            column.setStatus(1);
//            List<SysTableColumn> columns = columnDao.selectByModel(column);
//            TableModel tableModel = new TableModel();
//            tableModel.setTableName(table.getTableName());
//            tableModel.setTableRemark(table.getTableRemark());
//            LinkedList cLink = new LinkedList();
//            for (SysTableColumn c : columns) {
//                ColumnModel cm = new ColumnModel();
//                cm.setTableName(c.getTableName());
//                cm.setColumnDatatype(c.getColumnDatatype());
//                cm.setColumnName(c.getColumnName());
//                cm.setColumnRemark(c.getColumnRemark());
//                cm.setControlType(c.getControlType());
//                cm.setDefaultValue(c.getDefaultValue());
//                cm.setIsPrimaryKey(c.getIsPrimaryKey());
//                cm.setIsRequired(c.getIsRequired());
//                cm.setMaxLength(c.getMaxLength());
//                cm.setMinLength(c.getMinLength());
//                cm.setPlaceholder(c.getPlaceholder());
//                cLink.add(c);
//            }
//            if (columns.size() > 0) {
//                Map map = new HashMap();
//                map.put("table", tableModel);
//                map.put("columns", cLink);
//                map.put("sys", new MakeCodeUtils());
//                Map config = new HashMap();
//                config.put("package", "com.oa");//从配置里读取
//                map.put("config", config);
//                List<String> files = FileUtils.refreshFileList(template);
//                for (String file : files) {
//                    int lastIndex = file.lastIndexOf("/") + 1;
//                    String templatePath = file.substring(0, lastIndex);
//                    String templateName = file.substring(lastIndex);
//                    int lastDotIndex = file.lastIndexOf(".");
//                    String fileName = file.substring(0, lastDotIndex);//输入文件的全路径
//                    File tmpFile = new File(fileName);
//                    if (!tmpFile.isDirectory()) {
//                        fileName = fileName.replace("codetmpl", "code");
//                        FreeMarkerUtils.analysisTemplate(templatePath, templateName, fileName, map);
//                    }
//                }
//            }
//        }


        String templatePath = "oa/web/CodeTmpl/", templateName = "edit.html.ftl", fileName = "oa/web/CodeTmpl/edit.html";
        File dir = new File(templatePath);
        Map map = new HashMap();
        map.put("userName", "hello james");
        LinkedList link = new LinkedList();
        //List<SysUserBase> lst=new LinkedList<SysUserBase>();
        for (int i = 0; i < 100000; i++) {
            SysUserBase user = new SysUserBase();
            user.setUserName("中华鲟 " + i);
            link.add(user);
        }
        map.put("userList", link);
        // fileName=fileName+"1.html";
        long a = System.currentTimeMillis();
        analysisTemplate1(dir.getPath(), templateName, fileName, map);
        System.out.println("analysisTemplate1耗时：" + (System.currentTimeMillis() - a));

        long ab = System.currentTimeMillis();
        analysisTemplate(dir.getPath(), templateName, fileName, map);
        System.out.println("analysisTemplate耗时：" + (System.currentTimeMillis() - ab));

    }
}
